package com.hmyd.hmyd_android.ui;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hmyd.hmyd_android.AppBasic;
import com.hmyd.hmyd_android.R;
import com.hmyd.hmyd_android.commons.Constants;
import com.hmyd.hmyd_android.commons.UrlConstant;
import com.hmyd.hmyd_android.crypto.Crypto;
import com.hmyd.hmyd_android.dto.User;
import com.hmyd.hmyd_android.dto.VerifyCode;
import com.hmyd.hmyd_android.utils.MyToast;
import com.hmyd.hmyd_android.utils.PreferencesUtils;
import com.hmyd.hmyd_android.utils.Utils;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.shangzhu.apptrack.AppTrack_2423;

/**
 * 更换设备登录
 * 
 * @author wangc
 * 
 */
@ContentView(R.layout.activity_unforzenaccount)
public class ChangeDeviceLoginActivity extends BasicActivity {
	// 标题栏
	@ViewInject(R.id.home_title)
	public View home_title;
	@ViewInject(R.id.home_title_txt)
	public TextView home_title_txt;
	@ViewInject(R.id.home_right)
	public TextView home_right;

	@ViewInject(R.id.login_tips)
	private TextView login_tips;

	@ViewInject(R.id.verification_code)
	private Button verification_code;

	@ViewInject(R.id.verification_edit)
	private EditText verification_edit;

	private String mCodeId;
	String phoneNum;
	String passwd;

	private final int SEND_REGISTER_VERIFY_CODE = 0;
	private final int LOGIN = 1;

	// 获取验证码
	@OnClick({ R.id.verification_code, R.id.btn_login })
	public void onClick(View view) {
		RequestParams params = new RequestParams();
		switch (view.getId()) {
		case R.id.verification_code:
			params.addBodyParameter("mobile", phoneNum);
			onRequest(SEND_REGISTER_VERIFY_CODE, UrlConstant.SAFECODE, HttpMethod.POST, params);
			break;
		case R.id.btn_login:
			if (TextUtils.isEmpty(verification_edit.getText().toString().trim())) {
				MyToast.showHMToast(this, false, "请输入验证码");
				return;
			}
			params.addBodyParameter("username", phoneNum);
			params.addBodyParameter("password", passwd);
			params.addBodyParameter("codeId", mCodeId);
			params.addBodyParameter("verifyCode", verification_edit.getText().toString().trim());

			onRequest(LOGIN, UrlConstant.LOGIN, HttpMethod.POST, params);

			break;

		default:
			break;
		}

	}

	@Override
	public void onPostSuccess(int postId, String result) {
		Gson gson = new Gson();
		switch (postId) {
		case SEND_REGISTER_VERIFY_CODE:
			handler.postDelayed(runnable, 0);
			java.lang.reflect.Type type = new TypeToken<VerifyCode>() {
			}.getType();
			VerifyCode verifyCode = gson.fromJson(result, type);
			mCodeId = verifyCode.codeId;

			break;
		case LOGIN:
			java.lang.reflect.Type type2 = new TypeToken<User>() {
			}.getType();
			User user = gson.fromJson(result, type2);

			PreferencesUtils.putString(this, PreferencesUtils.USER_PHONE, phoneNum);
			PreferencesUtils.putString(this, PreferencesUtils.USER_PASSWORD,
					Crypto.encryptAES(passwd, Crypto.PRIVATEKEY));

			AppBasic.isLogin = true;
			AppBasic.isCheckIned = user.isCheckIned;
			AppBasic.totalScore = user.score;
			AppBasic.certNo = user.certNo;
			AppBasic.realName = user.realName;
			AppBasic.avatar = user.avatar;
			AppBasic.username = user.username;
			AppBasic.nickname = user.nickname;
			AppBasic.urlToken = user.urlToken;
			AppBasic.securityLevel = user.securityLevel;
			AppBasic.isSetSecurityCode = user.isSetSecurityCode;
			AppBasic.tel = user.tel;
			AppBasic.email = user.email;
			AppBasic.isVerifiedEmail = user.isVerifiedEmail;
			AppBasic.isSetSecurityQuestion = user.isSetSecurityQuestion;
			AppBasic.unReadMessageCount = user.unReadMessageCount;
			AppBasic.bindQQ = user.bindQQ;
			AppBasic.isBind = user.isBind;
			AppBasic.rewardScore = user.rewardScore;
			AppBasic.nextTimeScore = user.nextTimeScore;
			AppBasic.isCanUpdateNickname = user.isCanUpdateNickname;

			MyToast.showToast(this, "登录成功");
			// 加入99统计
			AppTrack_2423.countView(Constants.LoginPageTopic, "登录页面", "");

			Intent intent = new Intent();
			intent.putExtra("loginSuccess", true);
			setResult(RESULT_OK, intent);

			finish();

			break;

		default:
			break;
		}

	}

	@Override
	public void onPostFailure(int postId, String msg) {

	}

	@Override
	protected void setParams() {

		home_title.setOnTouchListener(touch);
		home_title_txt.setText("登录");

		phoneNum = getIntent().getStringExtra("phone");
		passwd = getIntent().getStringExtra("passwd");
		login_tips.setText("由于你在新设备上登录，需要验证\n  你的手机号" + "(" + Utils.hidePhone(phoneNum) + ")");

	}

	@Override
	protected void leftButton() {
		AppBasic.getInstance().finishCurrentActivity();
	}

	@Override
	protected void rightButton() {

	}

	private int second = 60;
	Handler handler = new Handler();
	Runnable runnable = new Runnable() {
		@Override
		public void run() {
			if (second >= 0) {
				verification_code.setText(second-- + "s");
				verification_code.setEnabled(false);
			} else {
				verification_code.setText(R.string.register_get_code);
				verification_code.setEnabled(true);

				second = 60;

				Message message = new Message();
				message.what = 1;
				handlerStop.sendMessage(message);
			}

			handler.postDelayed(this, 1000);
		}
	};

	final Handler handlerStop = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				handler.removeCallbacks(runnable);
				break;
			}
			super.handleMessage(msg);
		}
	};

}
